package com.kedou.sdk.core;

import android.text.TextUtils;
import android.util.Log;

import com.kedou.sdk.JuHaoWanSDK;
import com.kedou.sdk.handler.AsyncResponseHandler;
import com.kedou.sdk.handler.ResponseHanderInterface;
import com.kedou.sdk.params.AccountInfosRequestParams;
import com.kedou.sdk.params.AccountInfosTokenRequestParams;
import com.kedou.sdk.params.ActivityRequestParams;
import com.kedou.sdk.params.AgreementRequestParams;
import com.kedou.sdk.params.AlipayAuthRequestParams;
import com.kedou.sdk.params.AlipayRealnameParams;
import com.kedou.sdk.params.BaseRequestParams;
import com.kedou.sdk.params.BindPhoneReuqestParams;
import com.kedou.sdk.params.BoxLoginRequestParams;
import com.kedou.sdk.params.CheckVersionRequestParams;
import com.kedou.sdk.params.ConfigInfoRequestParams;
import com.kedou.sdk.params.CreateOrderRequestParams;
import com.kedou.sdk.params.CreatePlatformOrderRequestParams;
import com.kedou.sdk.params.LoginRequestParams;
import com.kedou.sdk.params.LogoutRequestParams;
import com.kedou.sdk.params.ModifyPasswordReuqestParams;
import com.kedou.sdk.params.PayChannelReuqestParams;
import com.kedou.sdk.params.PlatformCoinDetailParams;
import com.kedou.sdk.params.PlatformCoinRequestParams;
import com.kedou.sdk.params.PostRequestParams;
import com.kedou.sdk.params.PushInfoRequestParams;
import com.kedou.sdk.params.QuickRegisterRequestParams;
import com.kedou.sdk.params.RedpacakgeBindReuqestParams;
import com.kedou.sdk.params.RedpacakgeCashOutReuqestParams;
import com.kedou.sdk.params.RedpacakgeGetReuqestParams;
import com.kedou.sdk.params.RedpacakgeReuqestParams;
import com.kedou.sdk.params.RegisterRequestParams;
import com.kedou.sdk.params.RewardVideoRequestParams;
import com.kedou.sdk.params.RoleInfoRequestParams;
import com.kedou.sdk.params.SendVerifyReuqestParams;
import com.kedou.sdk.params.TencentLoginRequestParams;
import com.kedou.sdk.params.UuidRequestParams;
import com.kedou.sdk.utils.AndroidDeviceGenerator;
import com.kedou.sdk.utils.AndroidEmulatorChecker;
import com.kedou.sdk.utils.WL;
import com.kedou.sdk.utils.XmlUtils;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by Administrator on 2017/5/31 0031.
 */

public final class HttpEngine {

    private static final String TAG = HttpEngine.class.getSimpleName();

    ExecutorService httpThreadPool;

    HashMap<Integer, HttpEngineTask> tasks;

    HttpEngine(int threadPoolSize) {
        if(threadPoolSize <= 1){
            httpThreadPool = Executors.newSingleThreadExecutor();
        }else{
            httpThreadPool = Executors.newFixedThreadPool(threadPoolSize);
        }
        tasks = new HashMap<Integer, HttpEngineTask>();
    }


    public void shutdown(){
        if(httpThreadPool != null && !httpThreadPool.isShutdown()){
            httpThreadPool.shutdown();
            httpThreadPool = null;
            WL.d(TAG, "Destroy HttpEngine thread pool");
        }
    }

    public boolean isShutdown(){
        if(httpThreadPool == null){
            return true;
        }
        return httpThreadPool.isShutdown();
    }

    protected int submitTask(final HttpEngineTask task){
        if(httpThreadPool != null && !httpThreadPool.isShutdown()){
            final int taskId = task.getCurrentTaskId();
            tasks.put(taskId, task);
            httpThreadPool.execute(task);
            WL.d(TAG, "Submit new task, id: " + taskId);
            return taskId;
        }
        return -1;
    }

    public void cancelTask(int taskId){
        WL.d(TAG, "Cancel old task, id: " + taskId);
        HttpEngineTask task = tasks.remove(taskId);
        if(task != null){
            task.cancel();
        }
    }

    protected int get(String url, AsyncResponseHandler handler) {
        ResponseHanderInterface handlerInterface = handler == null ? null : handler.getResponseHanderInterface();
        HttpEngineTask task = HttpEngineTask.createHttpGetEngineTask(url, handlerInterface);
        return submitTask(task);
    }

    protected int post(String url, PostRequestParams requestParams, AsyncResponseHandler handler) {
        ResponseHanderInterface handlerInterface = handler == null ? null : handler.getResponseHanderInterface();
        HttpEngineTask task = HttpEngineTask.createHttpPostEngineTask(url, requestParams, handlerInterface);
        return submitTask(task);
    }

    public int getPlatformConfig(String url, ConfigInfoRequestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }
    public int getAgreement(String url, AgreementRequestParams requestParams, AsyncResponseHandler handler){
        return post(url, createAgreementRequestParams(requestParams), handler);
    }

    public int getAccountInfosByPhone(String url, AccountInfosRequestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }
    public int getAccountInfosByToken(String url, AccountInfosTokenRequestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }

    public int tencentLogin(String url, TencentLoginRequestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }
    public int getUuid(String url, UuidRequestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }

    public int login(String url, LoginRequestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }
    public int login(String url, BoxLoginRequestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }

    public int quickRegister(String url, QuickRegisterRequestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }

    public int register(String url, RegisterRequestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }

    public int logout(String url, LogoutRequestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }
    public int commenPost(String url, BaseRequestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }

    public int sendPhoneVerify(String url, SendVerifyReuqestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }

    public int bindPhoneNumber(String url, BindPhoneReuqestParams requestParams, AsyncResponseHandler handler){
       return post(url, createCommonRequestParams(requestParams), handler);
    }
    public int alipayAuth(String url, AlipayAuthRequestParams requestParams, AsyncResponseHandler handler){
       return post(url, createCommonRequestParams(requestParams), handler);
    }
    public int alipayRealname(String url, AlipayRealnameParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }

    public int modifyPassword(String url, ModifyPasswordReuqestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }

    public int createOrder(String url, CreateOrderRequestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }
    public int createPlatCoinOrder(String url, CreatePlatformOrderRequestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }
    public int platformCoin(String url, PlatformCoinRequestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }
    public int platformCoinDetail(String url, PlatformCoinDetailParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }

    public int getPayChannel(String url, PayChannelReuqestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }

    public int uploadRoleInfo(String url, RoleInfoRequestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }

    public int checkVersion(String url, CheckVersionRequestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }

    public int getGameActivityInfo(String url, ActivityRequestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }

    public int getRedpackageInfo(String url, RedpacakgeReuqestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }
    public int getRedpackage(String url, RedpacakgeGetReuqestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }
    public int redpackageBind(String url, RedpacakgeBindReuqestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }
    public int redpackageCashOut(String url, RedpacakgeCashOutReuqestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }

    public int getGamePushInfo(String url, PushInfoRequestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }

    public int reportVideoReward(String url, RewardVideoRequestParams requestParams, AsyncResponseHandler handler){
        return post(url, createCommonRequestParams(requestParams), handler);
    }

    private PostRequestParams createAgreementRequestParams(BaseRequestParams requestParams){
        if(requestParams != null){
            String ttChannel = JuHaoWanSDK.getInstance().getTouTiaoChannel();
            if(TextUtils.isEmpty(ttChannel)){
                requestParams.setChannelId(XmlUtils.getSdkChannelId());
            }else {
                requestParams.setChannelId(ttChannel);
            }

            requestParams.setSdk_version(XmlUtils.getSdkVersionName());
            requestParams.setTimestamp(String.valueOf(System.currentTimeMillis()));
            String noncestr =  UUID.randomUUID().toString();
            requestParams.setNoncestr(noncestr);
//            requestParams.setDeviceId(AndroidDeviceGenerator.getDeviceID(WanSDK.getInstance().getApplicationContent()));
//            requestParams.setIsSimulator(AndroidEmulatorChecker.isAndroidEmulator()?1:2);
//            requestParams.setMac(AndroidDeviceGenerator.getMacAddress(WanSDK.getInstance().getApplicationContent()));
//            requestParams.setModel(AndroidDeviceGenerator.getAndroidDeviceModel());
            HttpEngineConduits conduits = HttpEngineApi.getInstance().getEngineConduits();
            if(!TextUtils.isEmpty(conduits.readDeviceCode())){
                requestParams.setDeviceCode(conduits.readDeviceCode());

            }
            Log.d("Random string", noncestr);
        }
        return PostRequestParams.createRequestParams(requestParams);
    }


    private PostRequestParams createCommonRequestParams(BaseRequestParams requestParams){
        if(requestParams != null){
            String ttChannel = JuHaoWanSDK.getInstance().getTouTiaoChannel();
            if(TextUtils.isEmpty(ttChannel)){
                requestParams.setChannelId(XmlUtils.getSdkChannelId());
            }else {
                requestParams.setChannelId(ttChannel);
            }

            requestParams.setSdk_version(XmlUtils.getSdkVersionName());
            requestParams.setTimestamp(String.valueOf(System.currentTimeMillis()));
            String noncestr =  UUID.randomUUID().toString();
            requestParams.setNoncestr(noncestr);
//            requestParams.setDeviceId(AndroidDeviceGenerator.getDeviceID(JuHaoWanSDK.getInstance().getApplicationContent()));
            requestParams.setIsSimulator(AndroidEmulatorChecker.isAndroidEmulator()?1:2);
//            requestParams.setMac(AndroidDeviceGenerator.getMacAddress(WanSDK.getInstance().getApplicationContent()));
//            requestParams.setModel(AndroidDeviceGenerator.getAndroidDeviceModel());
            HttpEngineConduits conduits = HttpEngineApi.getInstance().getEngineConduits();
            if(!TextUtils.isEmpty(conduits.readDeviceCode())){
//                requestParams.setDeviceCode(conduits.readDeviceCode());

                requestParams.setDeviceId(conduits.readDeviceCode());

            }
            Log.d("Random string", noncestr);
        }
        return PostRequestParams.createRequestParams(requestParams);
    }

}
